﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Entities;
using Sustainalytics.Synchronization.Validation.Entities.CorporateGovernance;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.ValidationRules.CorporateGovernance
{
    public class GovernanceIndicatorScoreChangeYellowRule : Rule<GovernanceValidationProfile>
    {
        public override Severity Severity => Severity.Yellow;
        public override BusinessResearchProduct BusinessResearchProduct => BusinessResearchProduct.CorporateGovernance;
        public override string Code => "YR8";
        public override string InformationalMessage => "Indicators Score change of +/-40-90 points";

        public GovernanceIndicatorScoreChangeYellowRule()
        {
            For(x => x.GovernanceIndicators).When(Validator).WithKey(x => x.CompanyId)
                .WithMessage("The company {0} #{1}# has indicators score with a change of +/-40-90 Points");
        }

        private bool Validator(GovernanceValidationProfile validatedEntity, GovernanceValidationProfile referenceEntity)
        {
            var validatedIndicators = (List<GovernanceIndicator>)GetValue(validatedEntity);
            var referenceIndicators = (List<GovernanceIndicator>)GetValue(referenceEntity);

            if (validatedIndicators == null || referenceIndicators == null)
                return false;

            var triggerIndicators = (from referenceIndicator in referenceIndicators
                                     let validatedIndicator = validatedIndicators.FirstOrDefault(x => string.Equals(x.Number, referenceIndicator.Number, StringComparison.InvariantCultureIgnoreCase))
                                     where validatedIndicator != null
                                        && !validatedIndicator.Number.Contains("CG.6")
                                        && Math.Abs(validatedIndicator.Score - referenceIndicator.Score) >= 40 
                                        && Math.Abs(validatedIndicator.Score - referenceIndicator.Score) <= 90
                                     select validatedIndicator.Number);

            if (!triggerIndicators.Any())
                return true;

            SetTriggersMessages(triggerIndicators);

            return false;
        }
    }
}
